<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace app\shop\api;

use app\common\api\BaseApi;
use app\shop\model\SearchWords;
use app\system\api\UserMemberApi;
// use app\extend\Page;

class SearchWordsApi extends BaseApi{

	const ADD              = "shop/SearchWordsApi/add";
	const DELETE           = "shop/SearchWordsApi/delete";
	const SAVE             = "shop/SearchWordsApi/save";
	const SAVE_BY_ID       = "shop/SearchWordsApi/saveByID";
	const COUNT            = "shop/SearchWordsApi/count";
	const GET_INFO         = "shop/SearchWordsApi/getInfo";
	const QUERY            = "shop/SearchWordsApi/query";
	const QUERY_NO_PAGING  = "shop/SearchWordsApi/queryNoPaging";
	const QUERY_WITH_COUNT = "shop/SearchWordsApi/queryWithCount";
	/** private */
	const ADD_ONE = "shop/SearchWordsApi/addOne";
	const FIND_S  = "shop/SearchWordsApi/finds";

	protected function _init(){
		$this -> model = new SearchWords();
	}

	public function addOne($name= ''){
		$name = trim($name);
		if($name){
			$r = $this->model->where(['word'=>$name])->count();
			if(false === $r) return $this->apiReturnErr($this->model->getDbError());
			if($r){
				//edit
				$r = $this->setInc(['word'=>$name],'cnt',1);
			}else{
				//add
				$r = $this->add(['word'=>$name,'cnt'=>1]);
			}
			if(!$r['status']) return $this->apiReturnErr($r['info']);
			return $this->apiReturnSuc('pass');
		}else{
			return $this->apiReturnErr('invalid name');
		}
	}
	/**
	 * 获取$type类型的标签$number个
	 * @param  [type] $type   0=>随机,1=>最新,2=>最热
	 * @param  [type] $number [description]
	 * @return [type]         [description]
	 */
	public function finds($type,$number,$field){
		$type   = intval($type);
		$number = intval($number);
		$order  = 'id desc';
		if(0 === $type){
			$order_1 = ['id','word','cnt'];
			$order_2 = ['desc','asc'];
			$order = $order_1[array_rand($order_1)].' '.$order_2[array_rand($order_2)];
			$max = intval($this->model->count());
			if($max>1 && $max>$number){
				$start = floor(mt_rand(0,$max-$number-1));

			}else{
				$start = 0;
			}
			// trace('---'.$start.'---'.$number.'---'.$max);
			$res   = $this->model->order($order)->limit($start,$number)->field($field)->select();
			if(false === $res) return $this->apiReturnErr($this->model->getDbError());
			return $this->apiReturnSuc($res);
		}else if(1 === $type){
			//最新
			$order = 'id desc';
		}else if(2 === $type){
			//最热
			$order = 'cnt desc';
		}
		$result = $this->model->order($order)->limit($number)->field($field)->select();
		if(false === $result){
			return $this->apiReturnErr($this->model->getDbError());
		}else{
			return $this->apiReturnSuc($result);
		}
	}
}